package com.work.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.work.work.entity.Notification;
import com.work.work.mapper.NotificationMapper;
import com.work.work.service.NotificationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification> implements NotificationService {

    @Override
    public Page<Notification> getReceivedNotifications(Integer receiverId, Integer current, Integer size) {
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getReceiverId, receiverId)
                .orderByDesc(Notification::getSendTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public Page<Notification> getSentNotifications(Integer senderId, Integer current, Integer size) {
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getSenderId, senderId)
                .orderByDesc(Notification::getSendTime);
        return page(new Page<>(current, size), queryWrapper);
    }

    @Override
    public List<Notification> getUnreadNotifications(Integer receiverId) {
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getReceiverId, receiverId)
                .eq(Notification::getIsRead, 0)
                .orderByDesc(Notification::getSendTime);
        return list(queryWrapper);
    }

    @Override
    @Transactional
    public boolean markAsRead(Integer notificationId) {
        Notification notification = getById(notificationId);
        if (notification != null) {
            notification.setIsRead(1);
            return updateById(notification);
        }
        return false;
    }

    @Override
    @Transactional
    public boolean markAllAsRead(Integer receiverId) {
        LambdaQueryWrapper<Notification> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notification::getReceiverId, receiverId)
                .eq(Notification::getIsRead, 0);

        Notification updateEntity = new Notification();
        updateEntity.setIsRead(1);

        return update(updateEntity, queryWrapper);
    }
}